<?php

namespace app\controller\web;

use app\exception\ErrnoPlus;
use app\service\UserDeviceBindingService;
use app\service\UserDeviceShareService;
use app\service\UserService;
use app\validate\PageValidate;
use app\validate\UserDeviceShareValidate;
use share\exception\ApiException;
use share\service\UserBaseService;
use share\utils\Helper;

class UserDeviceShareController extends WebBaseController{

    public function initValidate(){        
        $this->validate = new UserDeviceShareValidate();
    }

    /**
     * 列表 搜索
     */
    public function list_action(){
        $page = $this->check('pageInfo',null,(new PageValidate()));
        $input = $this->check();       
        $data = UserDeviceShareService::getListInfo($input,$page);
        // $data = Helper::arrayListReplaceKey($data,[
        //     'user_id' => 'userId',
        //     'iot_id' => 'iotId',  
        //     'share_id' => 'shareId', 
        //     'main_id' => 'mainId',     
        // ]);
        $shareUids = array_column($data,'share_uid');
        $adminUids = array_column($data,'admin_uid');
        $uids = Helper::arraySmartUnique(array_merge($shareUids,$adminUids));
        $users = UserBaseService::getAll($uids);
        $res = [];
        foreach($data as $item){
            $tmp = $item;
            $shareUser = Helper::filterOne($users,['id' => $item['share_uid']]);
            $adminUser = Helper::filterOne($users,['id' => $item['admin_uid']]);
            $tmp['iotId'] = $item['iot_id'];
            $tmp['mainId'] = $item['main_id'];
            $tmp['userId'] = $adminUser ? $adminUser ['user_id'] : '';
            $tmp['shareId'] = $shareUser ? $shareUser ['user_id'] : '';
            $res[] = $tmp;
        }
        $total = UserDeviceShareService::getListCountInfo($input);
        return self::ok(self::formatPageData($page,$total,$res));
    }

    /**
     * 分享的详情
     */
    public function detail_action(){
        $id = $this->request->param('id');
        if(empty($id)){
            throw new ApiException("id lost",ErrnoPlus::COMMON_ERROR);
        }
        $res = UserDeviceShareService::shareDetailInfo($id);
        return self::ok($res);
    }

}